package com.rbac.controller;

import com.rbac.common.Result;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
	private static final Set<String> ALLOWED_TYPES = new HashSet<String>() {{
		add("image/jpeg");
		add("image/png");
	}};
	private static final long MAX_SIZE_BYTES = 2 * 1024 * 1024; // 2MB

	@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public Result<String> upload(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
		if (file == null || file.isEmpty()) {
			return Result.error("文件为空");
		}
		if (!ALLOWED_TYPES.contains(file.getContentType())) {
			return Result.error("仅支持 JPG/PNG 格式");
		}
		if (file.getSize() > MAX_SIZE_BYTES) {
			return Result.error("文件大小不能超过2MB");
		}

		try {
			Path projectRoot = Paths.get(System.getProperty("user.dir"));
			Path targetDir = projectRoot.resolve("src/main/resources/static/avatars");
			Files.createDirectories(targetDir);

			String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
			String ext = "";
			int dot = originalFilename.lastIndexOf('.');
			if (dot >= 0) {
				ext = originalFilename.substring(dot);
			}
			String filename = UUID.randomUUID().toString().replaceAll("-", "") + ext.toLowerCase();
			Path targetFile = targetDir.resolve(filename);
			// 使用 transferTo 写入文件，避免临时文件句柄未释放导致无法删除
			file.transferTo(targetFile.toFile());

			String contextPath = request.getContextPath(); // e.g. /api
			String url = (contextPath == null || contextPath.isEmpty() ? "" : contextPath) + "/avatars/" + filename;
			return Result.success(url);
		} catch (IOException e) {
			return Result.error("文件保存失败");
		}
	}
	
	// 调试接口：检查头像文件是否存在
	@GetMapping("/check/{filename}")
	public Result<Boolean> checkFile(@PathVariable String filename) {
		try {
			Path projectRoot = Paths.get(System.getProperty("user.dir"));
			Path targetDir = projectRoot.resolve("src/main/resources/static/avatars");
			Path targetFile = targetDir.resolve(filename);
			
			boolean exists = Files.exists(targetFile);
			return Result.success(exists);
		} catch (Exception e) {
			return Result.error("检查文件失败: " + e.getMessage());
		}
	}
} 